import axios from './api_config';
import path from './api_path';

let util = {

};

util.path = path;

util.title = function (title) {
    title = title || '智慧LNG全产业链大数据平台';
    window.document.title = title;
};

//post 请求
util.fetchPost = function (url, params = {}) {
    //请求加载
    // let token = localStorage.getItem('lng-token'); //h5 的浏览器缓存
    // if (token) {
    //     params.token = token;
    // }
    return new Promise((resolve, reject) => {
        axios({
            method: 'post',
            url: url,
            data: params,
            headers: {'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'}
        }).then((response) => {
            //console.log(JSON.stringify(response));
            //未登录 或者 登录过期
            // if (response.status === 401) {
            //     Cookies.remove('token');
            //     window.location.pathname = '/login';
            //     reject(response.data.msg);
            //     return;
            // }
            //
            // if(response.status !== 200){
            //     reject(response.data.msg);
            //     return;
            // }

            resolve(response.data);
        })
    })
};

util.fetchPostObj = function (url, params = {}) {
    //请求加载
    // let token = localStorage.getItem('lng-token'); //h5 的浏览器缓存
    // if (token) {
    //     params.token = token;
    // }
    return new Promise((resolve, reject) => {
        axios({
            method: 'post',
            url: url,
            data: params,
            headers: {'Accept': 'application/json', 'Content-Type': 'application/json'}
        }).then((response) => {
            //未登录 或者 登录过期
            // if (response.status === 401) {
            //     localStorage.removeItem('lng-token');
            //     window.location.pathname = '/login';
            //     reject(response.data.msg);
            //     return;
            // }
            //
            // if(response.status !== 200){
            //     reject(response.data.msg);
            //     return;
            // }

            resolve(response.data);
        })
    })
};

util.fetchGet = function (url, param = {}) {
    // let token = localStorage.getItem('lng-token'); //h5 的浏览器缓存
    // if (token) {
    //     param.token = token;
    // }
    let params = {
        params : param
    }
    return new Promise((resolve, reject) => {
        axios.get(url, params).then(res => {
            resolve(res.data)
        }).catch((error) => {
            reject(error)
        })
    })
};


util.setTitle = function (title) {
  document.title = title
  let mobile = navigator.userAgent.toLowerCase()
  if (/iphone|ipad|ipod/.test(mobile)) {
    let iframe = document.createElement('iframe')
    iframe.style.display = 'none'
    // iframe.setAttribute('src', '')
    let iframeCallback = function () {
      setTimeout(function () {
        iframe.removeEventListener('load', iframeCallback)
        document.body.removeChild(iframe)
      }, 0)
    }
    iframe.addEventListener('load', iframeCallback)
    document.body.appendChild(iframe)
  }
}

util.inOf = function (arr, targetArr) {
    let res = true;
    arr.map(item => {
        if (targetArr.indexOf(item) < 0) {
            res = false;
        }
    });
    return res;
};

util.oneOf = function (ele, targetArr) {
    if (targetArr.indexOf(ele) >= 0) {
        return true;
    } else {
        return false;
    }
};

util.showThisRoute = function (itAccess, currentAccess) {
    if (typeof itAccess === 'object' && itAccess.isArray()) {
        return util.oneOf(currentAccess, itAccess);
    } else {
        return itAccess === currentAccess;
    }
};

util.getRouterObjByName = function (routers, name) {
    let routerObj = {};
    routers.forEach(item => {
        if (item.name === 'otherRouter') {
            item.children.forEach((child, i) => {
                if (child.name === name) {
                    routerObj = item.children[i];
                }
            });
        } else {
            if (item.children.length === 1) {
                if (item.children[0].name === name) {
                    routerObj = item.children[0];
                }
            } else {
                item.children.forEach((child, i) => {
                    if (child.name === name) {
                        routerObj = item.children[i];
                    }
                });
            }
        }
    });
    return routerObj;
};

util.handleTitle = function (vm, item) {
    if (typeof item.title === 'object') {
        return vm.$t(item.title.i18n);
    } else {
        return item.title;
    }
};

util.setCurrentPath = function (vm, name) {
    let title = '';
    let isOtherRouter = false;
    vm.$store.state.routers.forEach(item => {
        if (item.children.length === 1) {
            if (item.children[0].name === name) {
                title = util.handleTitle(vm, item);
                if (item.name === 'otherRouter') {
                    isOtherRouter = true;
                }
            }
        } else {
            item.children.forEach(child => {
                if (child.name === name) {
                    title = util.handleTitle(vm, child);
                    if (item.name === 'otherRouter') {
                        isOtherRouter = true;
                    }
                }
            });
        }
    });
    let currentPathArr = [];
    if (name === 'home_index') {
        currentPathArr = [
            {
                title: util.handleTitle(vm, util.getRouterObjByName(vm.$store.state.routers, 'home_index')),
                path: '',
                name: 'home_index'
            }
        ];
    } else if ((name.indexOf('_index') >= 0 || isOtherRouter) && name !== 'home_index') {
        currentPathArr = [
            {
                title: util.handleTitle(vm, util.getRouterObjByName(vm.$store.state.routers, 'home_index')),
                path: '/home',
                name: 'home_index'
            },
            {
                title: title,
                path: '',
                name: name
            }
        ];
    } else {
        let currentPathObj = vm.$store.state.routers.filter(item => {
            if (item.children.length <= 1) {
                return item.children[0].name === name;
            } else {
                let i = 0;
                let childArr = item.children;
                let len = childArr.length;
                while (i < len) {
                    if (childArr[i].name === name) {
                        return true;
                    }
                    i++;
                }
                return false;
            }
        })[0];
        if (currentPathObj.children.length <= 1 && currentPathObj.name === 'home') {
            currentPathArr = [
                {
                    title: '首页',
                    path: '',
                    name: 'home_index'
                }
            ];
        } else if (currentPathObj.children.length <= 1 && currentPathObj.name !== 'home') {
            currentPathArr = [
                {
                    title: '首页',
                    path: '/home',
                    name: 'home_index'
                },
                {
                    title: currentPathObj.title,
                    path: '',
                    name: name
                }
            ];
        } else {
            let childObj = currentPathObj.children.filter((child) => {
                return child.name === name;
            })[0];
            currentPathArr = [
                {
                    title: '首页',
                    path: '/home',
                    name: 'home_index'
                },
                {
                    title: currentPathObj.title,
                    path: '',
                    name: currentPathObj.name
                },
                {
                    title: childObj.title,
                    path: currentPathObj.path + '/' + childObj.path,
                    name: name
                }
            ];
        }
    }
    vm.$store.commit('setCurrentPath', currentPathArr);

    return currentPathArr;
};

util.openNewPage = function (vm, name, argu, query) {
    let pageOpenedList = vm.$store.state.pageOpenedList;
    let openedPageLen = pageOpenedList.length;
    let i = 0;
    let tagHasOpened = false;
    while (i < openedPageLen) {
        if (name === pageOpenedList[i].name) {  // 页面已经打开
            vm.$store.commit('pageOpenedList', {
                index: i,
                argu: argu,
                query: query
            });
            tagHasOpened = true;
            break;
        }
        i++;
    }
    if (!tagHasOpened) {
        let tag = vm.$store.state.tagsList.filter((item) => {
            if (item.children) {
                return name === item.children[0].name;
            } else {
                return name === item.name;
            }
        });
        tag = tag[0];
        tag = tag.children ? tag.children[0] : tag;
        if (argu) {
            tag.argu = argu;
        }
        if (query) {
            tag.query = query;
        }
        vm.$store.commit('increateTag', tag);
    }
    vm.$store.commit('setCurrentPageName', name);
};

util.toDefaultPage = function (routers, name, route, next) {
    let len = routers.length;
    let i = 0;
    let notHandle = true;
    while (i < len) {
        if (routers[i].name === name && routers[i].redirect === undefined) {
            route.replace({
                name: routers[i].children[0].name
            });
            notHandle = false;
            next();
            break;
        }
        i++;
    }
    if (notHandle) {
        next();
    }
};

//下载
util.download = function(url){
    let $a = document.createElement('a');
    $a.setAttribute("href", url);
    $a.setAttribute("download", "");
    let evObj = document.createEvent('MouseEvents');
    evObj.initMouseEvent( 'click', true, true, window, 0, 0, 0, 0, 0, false, false, true, false, 0, null);
    $a.dispatchEvent(evObj);
}

//格式化时间
util.formatDate = function (date, fmt) {
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    }
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + ''
            fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str))
        }
    }
    return fmt
}

function padLeftZero (str) {
    return ('00' + str).substr(str.length)
}

//13位时间戳转化成yy-mm-dd hh:mm:ss
util.getFormatDate = function (inputTime) {
    let date = new Date(inputTime);
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    let h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    let minute = date.getMinutes();
    let second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
};

//时间戳转化成yy-mm-dd
util.getDate = function (inputTime) {
    let date = new Date(inputTime);
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    return y + '-' + m + '-' + d;
};

//时间戳转化成hh:mm:ss
util.getTime = function (inputTime) {
    let date = new Date(inputTime);
    let h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    let minute = date.getMinutes();
    let second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return h+':'+minute+':'+second;
};

//格式化时间
util.formatDate = function (date, fmt) {
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    };
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    };
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + '';
            fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str));
        }
    }
    return fmt;
};

//获取选中月的第一天和最后一天
util.getMonthFirstAndLastQuarterDay =function (year, month) {
    let firstDate = year + '-' + month + '-01';
    let day = new Date(year,month,0);
    let lastDate = year + '-' + month + '-' + day.getDate();//获取当月最后一天日期
    return [firstDate,lastDate];
};

//获取选中年的第一天和最后一天
util.getYearFirstAndLastQuarterDay =function (year) {
    let firstDate = year + '-' + '01-01';
    let lastDate = year + '-' + '12-31';
    return [firstDate,lastDate];
};

// 校验手机号
util.validatePhoneNumber = (rule, value, callback) => {
    let myreg = /^((0\d{2,3}-\d{7,8})|(1[1234567890]\d{9}))$/;
    if (!myreg.test(value)) {
        callback(new Error('请输入正确的电话号码'));
    } else {
        callback();
    }
};

// 校验身份证号
util.validateIdentityCard = (rule, value, callback) => {
    let myreg = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/;
    if (!myreg.test(value)) {
        callback(new Error('请输入正确的身份证号'));
    } else {
        callback();
    }
};

// 校验纯数字
util.validateNumber = (rule, value, callback) => {
    let myreg = /^\d*$/;
    if (!myreg.test(value)) {
        callback(new Error('请输入纯数字'));
    } else {
        callback();
    }
};

util.isNumber = (str) => {
    let reg = /^\d*$/;
    return reg.test(str);
};
util.isIdentityCard = (str) => {
    let reg = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/;
    return reg.test(str);
};
// 校验手机号
util.isPhoneNumber = (str) => {
    let reg = /^((0\d{2,3}-\d{7,8})|(1[1234567890]\d{9}))$/;
    return reg.test(str);
};
// 校验邮箱
util.isEmail = (str) => {
    let reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
    return reg.test(str);
};
// 校验ip
util.isIP = (str) => {
    let reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
    return reg.test(str);
};

// 校验小数点位数（小数点前面最多16位数字，小数点后面最多4位数字）
util.isDecimals = (str) => {
    let reg = /^([1-9]\d{0,15}|0)(\.\d{1,4})?$/;
    return reg.test(str);
};
// 同时验证手机号和座机号
util.isPhone = (str) => {
    let reg =  /^((0\d{2,3}-\d{7,8})|(1[1234567890]\d{9}))$/;
    return reg.test(str);
};
//校验营业执照编号
util.isBusinessLicense = (str) => {
    let reg =  /^(?:(?![IOZSV])[\dA-Z]){2}\d{6}(?:(?![IOZSV])[\dA-Z]){10}$/;
    return reg.test(str);
};
//校验正整数 positive integer
util.isPositiveInteger = (str) => {
  let reg =  /^[1-9]\d*$/;
  return reg.test(str);
};
//校验密码  只能输入6到20位字符、数字和下划线
util.isPassword = (str) => {
  let reg =  /^[a-z0-9]\w{5,19}$/i;
  return reg.test(str);
};
//只保留省的名称
util.checkProvinceName = (str) => {
  return str.replace(/市/g, "").replace(/省/g, "").replace(/自治区/g, "").replace(/回族自治区/g, "").replace(/维吾尔自治区/g, "").replace(/壮族自治区/g, "").replace(/特别行政区/g, "")
};
//判断是否是微信浏览器的函数
util.isWeiXin = function () {
  var ua = navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) == "micromessenger") {
    return true;
  } else {
    return false;
  }
};
function padLeftZero (str) {
    return ('00' + str).substr(str.length);
}


export default util;
